package com.ihr360.subscriber;

import com.google.common.collect.Lists;
import com.ihr360.commons.data.util.Pair;
import com.ihr360.insurance.model.dto.benefits.CompanyBenefit;
import com.ihr360.insurance.service.CompanyBenefitService;
import com.ihr360.insurance.service.StaffBenefitService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rx.functions.Action1;

import java.util.List;
import java.util.Set;

/**
 * @author Stone.Shi
 * @description
 * @date 2018-01-31 15:47:15.
 */
@Component
public class StaffBenefitDataChangeSubscriber {

    @Autowired
    private CompanyBenefitService companyBenefitService;

    @Autowired
    private StaffBenefitService staffBenefitService;

    public Action1<Pair<List<String>, Set<Long>>> syncSocialInsuranceCount = new Action1<Pair<List<String>, Set<Long>>>() {
        @Override
        public void call(Pair<List<String>, Set<Long>> pair) {
            if (pair == null) {
                return;
            }
            List<String> authStaffIds = pair.getFirst();
            Set<Long> affectedCompanyBenefitIds = pair.getSecond();
            if (CollectionUtils.isEmpty(authStaffIds)
                    || CollectionUtils.isEmpty(affectedCompanyBenefitIds)) {
                return;
            }

            List<CompanyBenefit> benefits = companyBenefitService.getCompanyBenefitsIn(Lists.newArrayList(affectedCompanyBenefitIds));
            benefits.forEach(item -> {
                Integer insuranceCount = staffBenefitService.getSocialInsuranceCount(item.getId(), authStaffIds);
                item.setStaffCount(insuranceCount);
            });
            companyBenefitService.saveBenefits(benefits);
        }
    };

    public Action1<Pair<List<String>, Set<Long>>> syncHouseFundCount = new Action1<Pair<List<String>, Set<Long>>>() {
        @Override
        public void call(Pair<List<String>, Set<Long>> pair) {
            if (pair == null) {
                return;
            }
            List<String> authStaffIds = pair.getFirst();
            Set<Long> affectedCompanyBenefitIds = pair.getSecond();
            if (CollectionUtils.isEmpty(authStaffIds)
                    || CollectionUtils.isEmpty(affectedCompanyBenefitIds)) {
                return;
            }

            List<CompanyBenefit> benefits = companyBenefitService.getCompanyBenefitsIn(Lists.newArrayList(affectedCompanyBenefitIds));
            benefits.forEach(item -> {
                Integer houseFundsCount = staffBenefitService.getHouseFundCount(item.getId(), authStaffIds);
                item.setStaffCount(houseFundsCount);
            });
            companyBenefitService.saveBenefits(benefits);
        }
    };
}
